package util

import (
	"Short_chain_cats/config"
	"Short_chain_cats/database"
	"context"
	"fmt"
	"math/rand"
	"net/smtp"
	"time"
)

// GenerateEmailCode 生成邮箱验证码
func GenerateEmailCode() string {
	rand.Seed(time.Now().UnixNano())
	code := rand.Intn(1000000)
	return fmt.Sprintf("%06d", code) // 返回6位数的验证码
}

// StoreEmailCode 缓存邮箱验证码
func StoreEmailCode(ctx context.Context, email, code string) error {
	key := fmt.Sprintf("verification_code:%s", email)
	err := database.RedisClient.Set(ctx, key, code, 5*time.Minute).Err()
	return err
}

// VerifyEmailCode 校验缓存的邮箱验证码
func VerifyEmailCode(ctx context.Context, email, code string) bool {
	key := fmt.Sprintf("verification_code:%s", email)
	storedCode, err := database.RedisClient.Get(ctx, key).Result()
	if err != nil || storedCode != code {
		return false
	}
	// 删除已验证的验证码
	database.RedisClient.Del(ctx, key)
	return true
}

// SendEmail 发送邮件,参数是邮箱和对应的验证码
func SendEmail(to, msg string) error {
	// QQ 邮箱的 SMTP 配置
	email := config.Email
	smtpHost := email.SmtpHost
	smtpPort := email.SmtpPort
	sender := email.Sender     // 你的QQ邮箱
	password := email.Password // QQ邮箱的SMTP授权码

	// 设置邮件内容
	subject := "邮件"
	message := fmt.Sprintf("From: %s\nTo: %s\nSubject: %s\n\n%s", sender, to, subject, msg)

	// 发送邮件
	auth := smtp.PlainAuth("", sender, password, smtpHost)
	err := smtp.SendMail(smtpHost+":"+smtpPort, auth, sender, []string{to}, []byte(message))
	return err
}
